<template>
  <div class="app-container">
    <div class="block">
      <el-row :gutter="12">
        <el-col :span="6">
          <el-input v-model="listQuery.title" placeholder="标题" />
        </el-col>

        <el-col :span="6">
          <el-button type="success" icon="el-icon-search" @click.native="search">{{
            $t('button.search')
          }}</el-button>
          <el-button type="primary" icon="el-icon-refresh" @click.native="reset">{{
            $t('button.reset')
          }}</el-button>
        </el-col>
      </el-row>
      <br />
      <el-row>
        <el-col :span="24">
          <el-button type="success" icon="el-icon-plus" @click.native="add">{{
            $t('button.add')
          }}</el-button>
          <el-button type="danger" icon="el-icon-delete" @click.native="remove">{{
            $t('button.delete')
          }}</el-button>
        </el-col>
      </el-row>
    </div>

    <el-table
      :data="list"
      v-loading="listLoading"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
      @current-change="handleCurrentChange"
    >
      <el-table-column label="ID" prop="id" />
      <el-table-column label="标题" title="title" />
      <el-table-column label="类别" prop="type" />
      <el-table-column label="url" prop="url" />
      <el-table-column label="图片">
        <template #default="{ row }">
          <el-image :src="row.img" :preview-src-list="[row.img]" style="width: 150px" />
        </template>
      </el-table-column>
    </el-table>

    <el-dialog :title="formTitle" :visible.sync="formVisible" width="70%">
      <el-form ref="form" :model="form" :rules="rules" label-width="150px">
        <el-row>
          <el-col :span="12">
            <el-form-item label="标题" prop="title">
              <el-input v-model="form.title" minlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="url" prop="url">
              <el-input v-model="form.url" minlength="1"></el-input>
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="类型">
              <el-select v-model="form.type" placeholder="请选择">
                <el-option
                  v-for="item in options"
                  :key="item.value"
                  :label="item.label"
                  :value="item.value"
                >
                </el-option>
              </el-select>
            </el-form-item>
          </el-col>

          <el-col :span="12">
            <el-form-item label="banner图片">
              <el-upload
                class="upload-demo"
                drag
                multiple="false"
                :action="uploadUrl"
                :headers="uploadHeaders"
                :before-upload="handleBeforeUpload"
                :on-success="handleUploadSuccess"
              >
                <i class="el-icon-upload"></i>
                <div class="el-upload__text">上传图片</div>
              </el-upload>
            </el-form-item>
          </el-col>
        </el-row>
        <el-form-item>
          <el-button type="primary" @click="save">{{ $t('button.submit') }}</el-button>
          <el-button @click.native="formVisible = false">{{ $t('button.cancel') }}</el-button>
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>
<script>
import { remove, getList, save } from '@/api/cms/banner';
import { getToken } from '@/utils/auth';
import { Loading } from 'element-ui';
import { getApiUrl } from '@/utils/utils';

export default {
  data() {
    return {
      uploadUrl: '',
      uploadFileId: '',
      uploadHeaders: {
        Authorization: '',
      },
      loadingInstance: {},
      formVisible: false,
      formTitle: '添加banner',
      deptList: [],
      isAdd: true,
      options: [
        { label: '首页', value: 'index' },
        { label: '新闻', value: 'news' },
        { label: '产品', value: 'product' },
        { label: '解决方案', value: 'solution' },
        { label: '案例', value: 'case' },
      ],
      form: {
        id: '',
        title: '',
        url: '',
        img: '',
        idFile: '',
        type: 'index',
      },
      listQuery: {
        title: undefined,
      },
      list: null,
      listLoading: true,
      selRow: {},
    };
  },
  computed: {
    rules() {
      return {
        title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
        url: [{ required: true, message: 'URL不能为空', trigger: 'blur' }],
      };
    },
  },
  created() {
    this.init();
  },
  methods: {
    init() {
      this.uploadUrl = getApiUrl() + '/file';
      this.uploadHeaders['Authorization'] = getToken();
      this.fetchData();
    },
    fetchData() {
      this.listLoading = true;
      getList(this.listQuery).then((response) => {
        this.list = response.data;
        for (var index in this.list) {
          let item = this.list[index];
          item.img = getApiUrl() + '/file/getImgStream?idFile=' + item.idFile;
          console.log(item);
        }

        this.listLoading = false;
      });
    },
    search() {
      this.fetchData();
    },
    reset() {
      this.listQuery.title = '';
      this.fetchData();
    },
    handleFilter() {
      this.getList();
    },
    handleCurrentChange(currentRow) {
      this.selRow = currentRow;
    },
    resetForm() {
      this.form = {
        id: '',
        title: '',
        url: '',
        idFile: this.uploadFileId,
        type: '',
      };
    },
    add() {
      this.resetForm();
      this.formTitle = '添加banner';
      this.formVisible = true;
      this.isAdd = true;
    },
    save() {
      this.$refs['form'].validate((valid) => {
        if (valid) {
          save({
            id: this.form.id,
            title: this.form.title,
            url: this.form.url,
            idFile: this.uploadFileId,
            type: this.form.type,
          }).then(() => {
            this.$message({
              message: this.$t('common.optionSuccess'),
              type: 'success',
            });
            this.fetchData();
            this.formVisible = false;
          });
        } else {
          return false;
        }
      });
    },
    checkSel() {
      if (this.selRow && this.selRow.id) {
        return true;
      }
      this.$message({
        message: this.$t('common.mustSelectOne'),
        type: 'warning',
      });
      return false;
    },
    remove() {
      if (this.checkSel()) {
        var id = this.selRow.id;
        this.$confirm(this.$t('common.deleteConfirm'), this.$t('common.tooltip'), {
          confirmButtonText: this.$t('button.submit'),
          cancelButtonText: this.$t('button.cancel'),
          type: 'warning',
        })
          .then(() => {
            remove(id).then(() => {
              this.$message({
                message: this.$t('common.optionSuccess'),
                type: 'success',
              });
              this.fetchData();
            });
          })
          .catch(() => {});
      }
    },
    handleBeforeUpload() {
      if (this.uploadFileId !== '') {
        this.$message({
          message: this.$t('common.mustSelectOne'),
          type: 'warning',
        });
        return false;
      }
      this.loadingInstance = Loading.service({
        lock: true,
        text: this.$t('common.uploading'),
        spinner: 'el-icon-loading',
        background: 'rgba(0, 0, 0, 0.7)',
      });
    },
    handleUploadSuccess(response) {
      this.loadingInstance.close();
      if (response.code === 20000) {
        console.log(response.data);
        this.uploadFileId = response.data.id;
        this.form.fileName = response.data.originalFileName;
      } else {
        this.$message({
          message: this.$t('common.uploadError'),
          type: 'error',
        });
      }
    },
  },
};
</script>

<style lang="scss" scoped>
@import '~@/styles/common.scss';
</style>
